package com.training.admin.web.controller.report;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.department.Department;
import com.training.admin.entity.principal.Principal;
import com.training.admin.entity.project.ProjectPhase;
import com.training.admin.entity.project.TrainingSurveyResult;
import com.training.admin.entity.search.ProjectAppraisalReportSearch;
import com.training.admin.entity.security.Login;
import com.training.admin.service.DepartmentService;
import com.training.admin.service.PrincipalService;
import com.training.admin.service.ReportService;
import com.training.admin.service.TrainingCategoryService;
import com.training.admin.service.TrainingSurveyResultService;
import com.training.admin.web.controller.view.ExcelTemplateView;
/**
 * 
 * @author sjh
 *
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-report")
public class ProjectAppraisalResultsController {
	
	@SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(TrainerReportController.class);

	@Autowired
	private TrainingCategoryService trainingCategoryService;
	@Autowired
	private PrincipalService principalService;
	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private ReportService reportService;
	@Autowired
	private TrainingSurveyResultService trainingSurveyResultService;


	/**
	 * 项目评估表查询条件输入
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/project-appraisal-results", method = RequestMethod.GET)
	@MenuSetting("submenu-project-appraisal-result")
	@SuppressWarnings("rawtypes")
	public ModelAndView projectAppraisalReportSearch(Page page) {
		ModelAndView modelAndView = new ModelAndView("report/project-appraisal-report-search");
		// 培训分类
		
        Map catMap = trainingCategoryService.getAllCategory();
		Map allCatMap = (Map) catMap.get("allCatMap");
		Map allNameIdMap = (Map) catMap.get("allNameIdMap");

		modelAndView.addObject("allCatMap", allCatMap);
		modelAndView.addObject("allNameIdMap", allNameIdMap);
		// 事业部
		List<Department> depList = new ArrayList<Department>();
		Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Principal principal = principalService.loadByEmail(login.getEmail());
		if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
			// 系统管理员
			depList = departmentService.listAll(Department.class);
		} else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
			// 事业部负责人
			depList.add(departmentService.load(Department.class, principal.getDepartmentId()));
		}
		modelAndView.addObject("departmentList", depList);

		return modelAndView;
	}

	/**
	 * 项目评估表
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/project-appraisal-results", method = RequestMethod.GET, params = "filter")
	@MenuSetting("submenu-project-appraisal-result")
	@SuppressWarnings("rawtypes")
	public ModelAndView onProjectAppraisalReportSearch(ProjectAppraisalReportSearch projectAppraisalReportSearch,
			Page page, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("report/project-appraisal-report");

		Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Principal principal = principalService.loadByEmail(login.getEmail());
		if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
			// 系统管理员
			// do nothing
		} else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
			// 事业部负责人
			projectAppraisalReportSearch.setDepartmentId(principal.getDepartmentId());
		}

		int totals = reportService.count(projectAppraisalReportSearch);
		if (totals > 0) {

			
            List reportList = reportService.search(projectAppraisalReportSearch, page.with(totals));
			List<ProjectPhase> projectPhases = new ArrayList<ProjectPhase>();
			for (int i = 0; i < reportList.size(); i++) {
				Object[] obj = (Object[]) reportList.get(i);
				ProjectPhase projectPhase = (ProjectPhase) obj[0];
				// set survey result / suggestion to each project/phase
				List<TrainingSurveyResult> trainingSurveyResultList = trainingSurveyResultService
						.listByProjectPhase(projectPhase.getId());
				int totalScore = 0;
				String suggestion = "";
				int j = 0;
				int scoreCount = 0;
				for (; j < trainingSurveyResultList.size(); j++) {
					TrainingSurveyResult trainingSurveyResult = trainingSurveyResultList.get(j);
					String inputValue = trainingSurveyResult.getInputValue();
					int inputScore = 0;
					boolean isScore = true;
					//add questin type check
					if(trainingSurveyResult.getType() !=null && !"select".equalsIgnoreCase(trainingSurveyResult.getType() )){
						isScore = false;
					}
					
					if(isScore){
						try {
							inputScore = Integer.parseInt(inputValue);
							if (inputScore>5){
								//not valid score
								isScore = false;
							}
						} catch (Exception exx) {
							// survey question is input string.
							isScore = false;
						}
					}
					if (isScore) {
						// 评分
						totalScore += inputScore;
						scoreCount++;
					} else {
						// 建议
						if (!StringUtil.isBlank(trainingSurveyResult.getInputValue())) {
							suggestion = suggestion + ";" + trainingSurveyResult.getInputValue();
						}
					}

				}
				if (j > 1) {
					if (scoreCount > 0)
						projectPhase.setSurveyResult("" + totalScore * 1.0 / scoreCount);
					if (!StringUtil.isBlank(suggestion)) {
						projectPhase.setSurveySuggestion(suggestion.substring(1));
					} else {
						projectPhase.setSurveySuggestion("");
					}
				}
				projectPhases.add(projectPhase);
			}

			modelAndView.addObject("projectPhases", projectPhases);
			modelAndView.addObject("recordCount", projectPhases.size());
			modelAndView.addObject("page", page);

		}

		modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));

		// 培训分类
		Map catMap = trainingCategoryService.getAllCategory();
		Map allCatMap = (Map) catMap.get("allCatMap");
		Map allNameIdMap = (Map) catMap.get("allNameIdMap");

		modelAndView.addObject("allCatMap", allCatMap);
		modelAndView.addObject("allNameIdMap", allNameIdMap);

		return modelAndView;
	}

	/**
	 * 讲师评估表查询条件
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/trainer-appraisal-results", method = RequestMethod.GET)
	@MenuSetting("submenu-trainer-appraisal-result")
	public ModelAndView trainerAppraisalReportSearch(Page page) {
		ModelAndView modelAndView = new ModelAndView("report/trainer-appraisal-report-search");

		return modelAndView;
	}
	
	/**
	 * 项目评估结果表 - 导出
	 * 
	 * @param search
	 * @return
	 */
	@RequestMapping(value = "/reports/project-appraisal-report-export", method = RequestMethod.GET)
	public ModelAndView onProjectAppraisalReportExport(ProjectAppraisalReportSearch projectAppraisalReportSearch,
			Page page) {

		ModelAndView modelAndView = new ModelAndView(
				new ExcelTemplateView("project-appraisal-result.xls", "project-appraisal-report.xls"));

		Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Principal principal = principalService.loadByEmail(login.getEmail());
		if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
			// 系统管理员
			// do nothing
		} else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
			// 事业部负责人
			projectAppraisalReportSearch.setDepartmentId(principal.getDepartmentId());
		}

		int totals = reportService.count(projectAppraisalReportSearch);
		if (totals > 0) {
			@SuppressWarnings("rawtypes")
            List reportList = reportService.searchForExport(projectAppraisalReportSearch);
			List<ProjectPhase> projectPhases = new ArrayList<ProjectPhase>();
			for (int i = 0; i < reportList.size(); i++) {
				Object[] obj = (Object[]) reportList.get(i);
				ProjectPhase projectPhase = (ProjectPhase) obj[0];
				// set survey result / suggestion to each project/phase
				List<TrainingSurveyResult> trainingSurveyResultList = trainingSurveyResultService
						.listByProjectPhase(projectPhase.getId());
				int totalScore = 0;
				String suggestion = "";
				int j = 0;
				int scoreCount = 0;
				for (; j < trainingSurveyResultList.size(); j++) {
					TrainingSurveyResult trainingSurveyResult = trainingSurveyResultList.get(j);
					String inputValue = trainingSurveyResult.getInputValue();
					int inputScore = 0;
					boolean isScore = true;
					//add questin type check
					if(trainingSurveyResult.getType() !=null && !"select".equalsIgnoreCase(trainingSurveyResult.getType() )){
						isScore = false;
					}
					
					if(isScore){
						try {
							inputScore = Integer.parseInt(inputValue);
							if (inputScore>5){
								//not valid score
								isScore = false;
							}
						} catch (Exception exx) {
							// survey question is input string.
							isScore = false;
						}
					}
					if (isScore) {
						// 评分
						totalScore += inputScore;
						scoreCount++;
					} else {
						// 建议
						if (!StringUtil.isBlank(trainingSurveyResult.getInputValue())) {
							suggestion = suggestion + ";" + trainingSurveyResult.getInputValue();
						}
					}

				}
				if (j > 1) {
					if (scoreCount > 0)
						projectPhase.setSurveyResult("" + totalScore * 1.0 / scoreCount);
					if (!StringUtil.isBlank(suggestion)) {
						projectPhase.setSurveySuggestion(suggestion.substring(1));
					} else {
						projectPhase.setSurveySuggestion("");
					}
				}
				projectPhases.add(projectPhase);
			}

			modelAndView.addObject("results", projectPhases);

		}

		return modelAndView;

	}
}
